const { Service } = require('dx-router-admin');
const { UniIdUsers } = require('dx-func-entity');
const createConfig = require('uni-config-center');

module.exports = class User extends Service {
	constructor(ctx) {
		super(ctx);
		this.entity = UniIdUsers;
		const uniIdConfig = createConfig({
			pluginId: 'uni-id', // 插件id
		});
		let passwordSecret = uniIdConfig.config('passwordSecret');
		if (ctx.utils.isArray(passwordSecret)) {
			this.passwordSecret = passwordSecret[0];
		} else {
			this.passwordSecret = passwordSecret;
		}
	}
	init() {
		this.$on('before_insert', function (param) {
			// 密码 为空 默认 123456
			let password = param.password || '123456';
			let { passwordHash, version } = this.$dx.utils.getPasswordExtMethod(this.passwordSecret.type, this.passwordSecret).encrypt(password);
			param.password = passwordHash;
			param.password_secret_version = version;
			return param;
		});
		this.$on('before_update', function (param) {
			if (param.password) {
				let { passwordHash, version } = this.$dx.utils.getPasswordExtMethod(this.passwordSecret.type, this.passwordSecret).encrypt(param.password);
				param.password = passwordHash;
				param.password_secret_version = version;
			} else {
				Reflect.deleteProperty(param, 'password');
			}
			return param;
		});
	}
	async toDayUser() {
		// 获取今日新增用户
		let now = new Date();
		let startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
		let timestamp = startOfDay.getTime();
		const dbCmd = this.$dx.db.command;
		const todayTotal = await this.where(
			{
				register_date: dbCmd.gte(timestamp),
			},
			true
		).count();
		return todayTotal;
	}
	// 三天内新增用户
	async threeDayUser() {
		let now = new Date();
		let startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
		let timestamp = startOfDay.getTime() - 3 * 24 * 60 * 60 * 1000;
		const dbCmd = this.$dx.db.command;
		const todayTotal = await this.where(
			{
				register_date: dbCmd.gte(timestamp),
			},
			true
		).count();
		return todayTotal;
	}
	// 七天内新增用户
	async sevenDayUser() {
		let now = new Date();
		let startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
		let timestamp = startOfDay.getTime() - 7 * 24 * 60 * 60 * 1000;
		const dbCmd = this.$dx.db.command;
		const todayTotal = await this.where(
			{
				register_date: dbCmd.gte(timestamp),
			},
			true
		).count();
		return todayTotal;
	}
	async toDayLogin() {
		// 获取今日登录用户
		let now = new Date();
		let startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
		let timestamp = startOfDay.getTime();
		const dbCmd = this.$dx.db.command;
		// const $ = this.$dx.db.command.aggregate;
		const todayTotal = await this.where(
			{
				last_login_date: dbCmd.gte(timestamp),
			},
			true
		).count();
		return todayTotal;
	}
	// 最近7天新增用户
	async getWeekRegUser() {
		//前七天
		let now = new Date();
		let startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
		let timestamp = startOfDay.getTime() - 7 * 24 * 60 * 60 * 1000;
		const $ = this.$dx.db.command.aggregate;
		// https://ask.dcloud.net.cn/question/113532
		let dateBase = $.dateFromParts({ year: 1970, month: 1, day: 1, hour: 8, minute: 0, second: 0, millisecond: 0, timezone: 'Asia/Shanghai' });
		const dbCmd = this.$dx.db.command;
		let { data } = await this.model
			.aggregate()
			.match({
				register_date: dbCmd.gte(timestamp),
			})
			.addFields({
				register_time: $.add([dateBase, $.multiply(['$register_date'])]),
			})
			.addFields({
				register_time: $.dateToString({ date: '$register_time', format: '%Y-%m-%d' }),
			})
			.group({
				_id: '$register_time',
				num: $.sum(1),
			})
			.end();
		const listMap = {};
		for (let item of data) {
			listMap[item._id] = item.num;
		}
		return listMap;
	}
	// 最近7天登录用户
	async getWeekLoginUser() {
		//前七天
		let now = new Date();
		let startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
		let timestamp = startOfDay.getTime() - 7 * 24 * 60 * 60 * 1000;
		const $ = this.$dx.db.command.aggregate;
		// https://ask.dcloud.net.cn/question/113532
		let dateBase = $.dateFromParts({ year: 1970, month: 1, day: 1, hour: 8, minute: 0, second: 0, millisecond: 0, timezone: 'Asia/Shanghai' });
		const dbCmd = this.$dx.db.command;
		let { data } = await this.model
			.aggregate()
			.match({
				last_login_date: dbCmd.gte(timestamp),
			})
			.addFields({
				last_login_time: $.add([dateBase, $.multiply(['$last_login_date'])]),
			})
			.addFields({
				last_login_time: $.dateToString({ date: '$last_login_time', format: '%Y-%m-%d' }),
			})
			.group({
				_id: '$last_login_time',
				num: $.sum(1),
			})
			.end();
		const listMap = {};
		for (let item of data) {
			listMap[item._id] = item.num;
		}
		return listMap;
	}
	async getApplicationUser() {
		const $ = this.$dx.db.command.aggregate;
		let { data } = await this.model
			.aggregate()
			.group({
				_id: '$dcloud_appid',
				num: $.sum(1),
			})
			.end();
		const appList = await this.$dx.service.app.getApplicationList();
		const appMap = {};
		for (let item of appList) {
			appMap[item.appid] = {
				name: item.name,
				num: data.reduce((total, current) => {
					if (current._id.includes(item.appid)) {
						return total + current.num;
					}
					return total;
				}, 0),
			};
		}
		return appMap;
	}
};
